<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>父组件访问子组件</title>
</head>
<body>
<div id="app">
    <cpn1 id="cpn1" ref="child1"></cpn1>
    <cpn2 id="cpn2" ref="child2"></cpn2>

    <button v-on:click="btnClicked">获取组件</button>
</div>
<template id="cpn">
    <h2>我是子组件</h2>
</template>

<script type="module">
    import {createApp, ref} from "../../../../js/vue.esm-browser.js";
    import {defineComponent} from "../../../../js/vue.esm-browser.js";

    let cpn1 = defineComponent(
        {
            template: "#cpn",

            setup(props, {expose}) {
                let name = ref("这个是 cpn1 组件的名称")

                function showName() {
                    console.log("这个是 cpn1 组件中的函数");
                }

                expose({
                    name,
                    showName,
                })

                return {
                    // name,
                    // showName,
                };
            }
        }
    );
    let cpn2 = defineComponent(
        {
            template: "#cpn",
            setup(props, context) {
                let name = ref("这个是 cpn2 组件的名称")

                function showName() {
                    console.log("这个是 cpn2 组件中的函数");
                }

                context.expose({
                    name,
                    showName,
                })

                return {
                    // name,
                    // showName,
                };
            }
        }
    );

    let app = createApp({
        setup() {

            // 使用组合式 API，引用将存储在与名字匹配的 ref 里
            let child1 = ref(null)
            let child2 = ref()
            // console.log(cpn1);

            function btnClicked() {
                /*// 通过原生 JS 得到的是 HTML 元素代码
                let cpn1 = document.getElementById("cpn1");
                console.log(cpn1);*/

                // 使用 ref 得到的是 RefImpl
                console.log(child1);
                console.log(child1.value);
                console.log(child1.value.name);
                child1.value.showName()

                console.log("-------------------------------");

                console.log(child2);
                console.log(child2.value);
                console.log(child2.value.name);
                child2.value.showName()



            }

            return {
                child1,
                child2,
                btnClicked
            }
        },
        components: {
            cpn1,
            cpn2,
        }
    })

    app.mount("#app")
</script>
</body>
</html>